export type AsrSuccess = {
  text: string;
  raw: unknown;
};

export type AsrError = {
  code: number;
  message: string;
  raw?: unknown;
};

export type AsrRequest = {
  accessToken: string;
  cuid: string;
  devPid?: number; // default 1537 (Mandarin with punctuation)
  format: 'wav' | 'pcm';
  sampleRate?: number; // default 16000
  channel?: 1; // forced 1
  speechBase64: string;
  rawBytesLength: number;
};

// 百度ASR支持的方言类型（实际支持的）
export const BAIDU_DIALECTS = {
  MANDARIN: 1537,        // 普通话（带标点）
  MANDARIN_NO_PUNC: 1536, // 普通话（无标点）
  CANTONESE: 1637,        // 粤语
  SICHUAN: 1837,          // 四川话
  ENGLISH: 1737,          // 英语
} as const;

// Use dev proxy to avoid CORS in browser. Vite rewrites /asr to Baidu server_api
const VOP_URL = '/asr';

export async function recognizeShortSpeech(req: AsrRequest): Promise<AsrSuccess> {
  const body = {
    format: req.format,
    rate: req.sampleRate ?? 16000,
    channel: req.channel ?? 1,
    cuid: req.cuid,
    token: req.accessToken,
    dev_pid: req.devPid ?? 1537,
    lan: 'zh',
    len: req.rawBytesLength,
    speech: req.speechBase64,
  } as const;

  const res = await fetch(VOP_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });

  if (!res.ok) {
    throw { code: res.status, message: `HTTP ${res.status}`, raw: await safeJson(res) } as AsrError;
  }

  const data = await res.json();
  if (data.err_no !== 0) {
    const message = typeof data.err_msg === 'string' ? data.err_msg : 'asr error';
    throw { code: data.err_no, message, raw: data } as AsrError;
  }

  const text: string = Array.isArray(data.result) && data.result.length > 0 ? data.result[0] : '';
  return { text, raw: data } as AsrSuccess;
}

async function safeJson(res: Response) {
  try {
    return await res.json();
  } catch {
    return undefined;
  }
}


